import React, {
    Component
} from 'react'
import {
    StyleSheet,
    View,
    Text,
    Switch,
    Dimensions,
} from 'react-native'

const { width, height } = Dimensions.get('window')
import Header from '../../components/common/Header'
import LabelBarWithSwitch from '../../components/styleCompoent/LabelBarWithSwitch'
import BoxShadowYaGuan from '../../components/common/BoxShadowYaGuan'
import {fetchDeviceDetailById, controlDevice } from '../../action/girlAction';
import { bindActionCreators } from 'redux';
import {connect} from 'react-redux';
const EntityLabels = require('../../constants/entities');
import assign from 'lodash/assign';
import NavigationBar from '../../components/common/NavigationBar'

class SmartSocket extends Component {
  constructor(props) {
    super(props)

    this._leftIconEvent = this._leftIconEvent.bind(this)
    this._rightIconEvent = this._rightIconEvent.bind(this)
    // 初始状态
    this.state = {
      switchValue1: false,
      switchValue2: false,
      switchValue3: false,
    }

  }
  componentWillMount() {

      const { fetchDeviceDetailById,  deviceId} = this.props;
      fetchDeviceDetailById(deviceId);
      this.convertPropsToStates(this.props);

  }
  convertPropsToStates(props) {
    const {devicesEntities, deviceId, actions, update} = props;
    const device = devicesEntities[deviceId];
    let data;
    if(update === 'update'){
      actions && actions.forEach(ele => {
        if (ele.switchMultiple1 === '1'){
          this.setState({
            switchValue1: true,
          })
        }

        if (ele.switchMultiple2 === '1'){
          this.setState({
            switchValue2: true,
          })
        }

        if (ele.switchChildLock === '1' || ele.switchChildLock === 'true'){
          this.setState({
            switchValue3: true,
          })
        }
      })

    }else {
      data =device && device.status;
      if (data){
        if (data.switchMultiple1 === '1'){
          this.setState({
            switchValue1: true,
          })
        }
        else {
          this.setState({
            switchValue1: false,
          })
        }
        if (data.switchMultiple2 === '1'){
          this.setState({
            switchValue2: true,
          })
        }
        else {
          this.setState({
            switchValue2: false,
          })
        }
        if (data.switchChildLock === '1'){
          this.setState({
            switchValue3: true,
          })
        }
        else {
          this.setState({
            switchValue3: false,
          })
        }
      }
    }


    const newState = assign({
      device
    });

    if (newState) {
      this.setState(newState);
    }
  }

  componentWillReceiveProps(nextProps) {
    this.convertPropsToStates((nextProps));
  }

  controlAir(params){
    const {controlDevice, deviceId} = this.props;
    controlDevice(params, deviceId);
  }
  render() {
    const rightElement = <Text style={styles.rightText} onPress={this._rightIconEvent}>保存</Text>
    const { device } = this.state;
    const status = device && device.status;
    const { update} = this.props;

    return (
        <View style = {styles.container}>
          <NavigationBar
              title={'10A智能插座'}
              statusBar={{backgroundColor: '#F4F4F4', barStyle: 'dark-content'}}
              navigator={this.props.navigator}
              rightButton={ update === 'update' ? rightElement : null}
              style={{backgroundColor: '#F4F4F4'}}
          />

          <View style={styles.topView}>
            <View>
              <View style={styles.titleView}>
                <Text style={styles.titleText}>累计用电172KW·h</Text>
              </View>
              <View style={styles.dataView}>
                <View style={styles.itemView}>
                  <Text style={styles.dataText}>1A</Text>
                  <Text style={styles.infoText}>有效电流</Text>
                </View>
                <View>
                  <Text style={styles.dataText}>220V</Text>
                  <Text style={styles.infoText}>有效电压</Text>
                </View>
              </View>
            </View>
          </View>
          <View style={styles.switchView}>
            <BoxShadowYaGuan
                barWidth={width-30}
                barHeight={142}
                renderItem={()=>{
                  return (
                      <View style={styles.boxShadowView}>
                        <View style={styles.power}>
                          <Text style={styles.powerText}>插孔开关1</Text>
                          <Switch
                              value={this.state.switchValue1}
                              onTintColor='#00A5AD'
                              onValueChange={
                                (value)=>{
                                  this.setState({
                                    switchValue1: value
                                  },()=>{
                                    const newAirParams = {'SwitchMultiple_1': value ? '1' : '0'};

                                    update !== 'update' && this.controlAir(newAirParams);
                                  })
                                }
                              }
                          />
                        </View>
                        <View style={styles.power}>
                          <Text style={styles.powerText}>插孔开关2</Text>
                          <Switch
                              value={this.state.switchValue2}
                              onTintColor='#00A5AD'
                              onValueChange={
                                (value)=>{
                                  this.setState({
                                    switchValue2: value
                                  },()=>{
                                    const newAirParams = {'SwitchMultiple_2': value ? "1" : '0'}
                                    update !== 'update' && this.controlAir(newAirParams);
                                  })
                                }
                              }
                          />
                        </View>
                      </View>
                  )}}
            />
          </View>
          <View style={styles.bottomSwitchView}>
            <LabelBarWithSwitch
                barWidth={width-30}
                barHeight={68}
                title="儿童锁"
                changeValue={(value)=>{
                  this.setState({
                    switchValue3: value
                  },()=>{
                    const newAirParams = {'SwitchChildLock': value ? "1" : '0'}
                    update !== 'update' && this.controlAir(newAirParams);
                  })
                }}
                value={this.state.switchValue3}
            />
          </View>
        </View>
    )
  }

  _leftIconEvent() {
    this.props.navigator.pop()
  }

  _rightIconEvent() {
    const {  device, switchValue1, switchValue2, switchValue3 } =this.state;
    const {  setParams, isUpdate} =this.props;
    const status = device && device.status;
    isUpdate(true);
    const params = {'switchMultiple1': switchValue1? "1" : '0','switchMultiple2': switchValue2? "1" : '0','switchChildLock': switchValue3? "1" : '0' }
    setParams(params);

  }
}


function mapDispatchToProps(dispatch) {
  const actions = {
    fetchDeviceDetailById,
    controlDevice
  };
  return bindActionCreators(actions, dispatch);
}

function mappingStateToProps(state, ownProps) {
  const entities= state['entities'];
  const devicesEntities = entities[EntityLabels.devices];
  return {
    devicesEntities,
  }
}

module.exports = connect(mappingStateToProps, mapDispatchToProps)(SmartSocket);

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#F4F4F4',
    flex: 1,
  },
  topView: {
    flex: 1,
    marginBottom: 25,
    justifyContent: 'center'
  },
  titleView: {
    alignItems: 'center',
    marginBottom: 30,
  },
  titleText: {
    color: '#333333',
    fontSize: 16
  },
  dataView: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  dataText: {
    color: '#333333',
    fontSize: 24
  },
  infoText: {
    color: '#575757',
    fontSize: 12
  },
  itemView: {
    alignItems: 'center'
  },
  switchView: {
    height: 142,
    marginBottom: 20,
    marginLeft: 15,
  },
  boxShadowView: {
    width: width - 30,
    height: 142,
    backgroundColor: '#fff',
    borderRadius: 6,
    flex:1,
  },
  powerText: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#333333',
    flex: 1,
  },
  power: {
    height: 71,
    backgroundColor: '#fff',
    borderRadius: 6,
    flexDirection:'row',
    alignItems: 'center',
    paddingLeft: 20,
    paddingRight: 20,
  },
  bottomSwitchView: {
    marginBottom: 90
  }
});
